<?php

/**
 * site actions.
 *
 * @package    MiMercado.es
 * @subpackage site
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class siteActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward404Unless($request->hasParameter('name'), "Debe enviar el parámetro 'name'.");
    $siteName = $request->getParameter('name');

    $this->site =  SiteTable::getSiteBySlug($siteName);
    $this->forward404Unless($this->site, "No se encontró el sitio '$siteName'.");

	$this->tags = $this->site->getProductTags();
	$this->articulos = ProductTable::getProductsForSite($this->site->getId());

	$user = $this->getUser()->getAttribute('user');
	$this->isSiteAdmin = $user && $this->getUser()->isAuthenticated() && $user->getSite()->getId() == $this->site->getId();
  }

  public function executeArticle(sfWebRequest $request)
  {
    $this->forward404Unless($request->hasParameter('slug'), "Debe enviar el parámetro 'slug'.");
    $slug = $request->getParameter('slug');

    $this->article =  ProductTable::getProductBySlug($slug);
    $this->forward404Unless($this->article, "No se encontró el artículo.");

    $this->site = $this->article->getSite();

    $user = $this->getUser()->getAttribute('user');
	$this->isSiteAdmin = $user && $this->getUser()->isAuthenticated() && $user->getSite()->getId() == $this->site->getId();
  }

  public function executeNewArticle(sfWebRequest $request)
  {
  	$user = $this->getUser()->getAttribute('user');
  	$this->forward404Unless($user, "No tiene permisos para acceder a esta sección.");

	$product = new Product;
	$product->setSite($user->getSite());
	$this->form = new ProductForm($product);

	if($request->isMethod('post')) {
	    $this->processForm($request, $this->form);
	}
  }

  public function executeEditArticle(sfWebRequest $request)
  {
  	if($request->isMethod('post')) {
  		$product_parameter = $request->getParameter('product');
  		$article_id = $product_parameter['id'];
  	}else{
  		$article_id = $request->getParameter('id');
  	}
	$this->forward404Unless($article_id, "Debe enviar el parámetro 'id'.");
	$article = $this->site = Doctrine::getTable('Product')->findOneById($article_id);
	$this->forward404Unless($article, "No se encontró el artículo.");
  	$user = $this->getUser()->getAttribute('user');
  	$isSiteAdmin = $user && $this->getUser()->isAuthenticated() && $user->getSite()->getId() == $article->getSite()->getId();
  	$this->forward404Unless($isSiteAdmin, "No tiene permisos para acceder a esta sección.");

	$this->nombre = $article->getName();
  	$this->form = new ProductForm($article);
	if($request->isMethod('post')) {
	    $this->processForm($request, $this->form);
	}

  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
  	$site = $this->getUser()->getAttribute('user')->getSite();
	$product_parameter = $request->getParameter('product');
	$product_parameter['site_id'] = $site->getId();

	$form->bind($product_parameter, $request->getFiles('product'));

	if($form->isValid()) {
		if ($form->getValue('remove_tags')) {
			foreach (preg_split('/\s*,\s*/', $form->getValue('remove_tags')) as $tag) {
				$form->getObject()->removeTag($tag);
			}
		}
		if ($form->getValue('new_tags')) {
			foreach (preg_split('/\s*,\s*/', $form->getValue('new_tags')) as $tag) {
				if ($tag == 'Agregar tags separados por comas') continue;
				$form->getObject()->addTag($tag);
			}
		}

		try {
			$article = $form->save();

		} catch (Doctrine_Validator_Exception $e) {

			$errorStack = $form->getObject()->getErrorStack();

			$message = get_class($form->getObject()) . ' tiene ' . count($errorStack) . " campo" . (count($errorStack) > 1 ?  's' : null) . " con errores: ";
			foreach ($errorStack as $field => $errors) {
				$message .= "$field (" . implode(", ", $errors) . "), ";
			}
			$message = trim($message, ', ');

			$this->getUser()->setFlash('error', $message);
			return sfView::SUCCESS;
		}
		$this->getUser()->setFlash('success', 'El artículo se guardó correctamente.');
		$this->redirect('articulo/'.$article->getSlug());

	}else{
		$this->getUser()->setFlash('error', 'Hubo un error en la validación del artículo.');
		return sfView::SUCCESS;
	}
  }

  public function executeDeleteArticle(sfWebRequest $request){
    $this->forward404Unless($request->hasParameter('id'), "Debe enviar el parámetro 'id'.");
  	$user = $this->getUser()->getAttribute('user');

  	$article = $this->site = Doctrine::getTable('Product')->findOneById($request->getParameter('id'));
  	$this->forward404Unless($article, "No se encontró el artículo.");

  	$isSiteAdmin = $user && $this->getUser()->isAuthenticated() && $user->getSite()->getId() == $article->getSite()->getId();
  	$this->forward404Unless($isSiteAdmin, "No tiene permisos para acceder a esta sección.");

  	$article->delete();

  	$this->getUser()->setFlash('success', 'El artículo se ha eliminado correctamente.');
  	$site = $user->getSite();
  	$this->redirect('site/index?name='.$site->getSlug());
  }

  public function executeCss(sfWebRequest $request){
  	$this->forward404Unless($request->hasParameter('site_id'), "Debe enviar el parámetro 'site_id'.");
	$this->site = Doctrine::getTable('Site')->findOneById($request->getParameter('site_id'));
  }

  public function executeConfigure(sfWebRequest $request){
  	//Si no esta logeado lo redirecciono al login
  	if($this->getUser()->isAuthenticated()){
  		if($this->getUser()->hasAttribute('user')){
  			$user = $this->getUser()->getAttribute('user');

  			if($site = $user->getSite()){
  				//si tiene sitio lo redirecciono al menu para editar su sitio
				$this->redirect('site/edit?id='.$site->getId());
  			}
  			//si no tiene sitio lo redirecciono al lugar para crearlo
  			$this->redirect('site/create');
  		}
  	}

  	$this->redirect('login/index');
  }

  public function executeMiMercado(sfWebRequest $request){
  	//Si no esta logeado lo redirecciono al login
  	if($this->getUser()->isAuthenticated()){
  		if($this->getUser()->hasAttribute('user')){
  			$user = $this->getUser()->getAttribute('user');

  			if($site = $user->getSite()){
  				//si tiene sitio lo redirecciono al menu para editar su sitio
				$this->redirect('site/index?name='.$site->getSlug());
  			}
  			//si no tiene sitio lo redirecciono al lugar para crearlo
  			$this->redirect('site/create');
  		}
  	}

  	$this->redirect('login/index');
  }

	public function executeCreate(sfWebRequest $request)
	  {
	  	$user = $this->getUser()->getAttribute('user');
	  	$this->forward404Unless($user, "No tiene permisos para acceder a esta sección.");

		$site = new Site;
		$site->setUser($user);
		$this->form = new SiteForm($site);

		if($request->isMethod('post')) {
		    $this->processSiteForm($request, $this->form);
		}
	  }

	  public function executeEdit(sfWebRequest $request)
	  {
	  	if($request->isMethod('post')) {
	  		$site_parameter = $request->getParameter('site');
	  		$site_id = $site_parameter['id'];
	  	}else{
	  		$site_id = $request->getParameter('id');
	  	}
		$this->forward404Unless($site_id, "Debe enviar el parámetro 'id'.");
		$site = Doctrine::getTable('Site')->findOneById($site_id);
		$this->forward404Unless($site, "No se encontró el sitio.");
	  	$user = $this->getUser()->getAttribute('user');
	  	$isSiteAdmin = $user && $this->getUser()->isAuthenticated() && $user->getSite()->getId() == $site->getId();
	  	$this->forward404Unless($isSiteAdmin, "No tiene permisos para acceder a esta sección.");

		$this->nombre = $site->getName();
	  	$this->form = new SiteForm($site);
		if($request->isMethod('post')) {
		    $this->processSiteForm($request, $this->form);
		}
	  }

  protected function processSiteForm(sfWebRequest $request, sfForm $form)
  {
  	$user = $this->getUser()->getAttribute('user');
	$site_parameter = $request->getParameter('site');
	$site_parameter['user_id'] = $user->getId();

	$form->bind($site_parameter, $request->getFiles('site'));

	if($form->isValid()) {

		try {
			$site = $form->save();

		} catch (Doctrine_Validator_Exception $e) {

			$errorStack = $form->getObject()->getErrorStack();

			$message = get_class($form->getObject()) . ' tiene ' . count($errorStack) . " campo" . (count($errorStack) > 1 ?  's' : null) . " con errores: ";
			foreach ($errorStack as $field => $errors) {
				$message .= "$field (" . implode(", ", $errors) . "), ";
			}
			$message = trim($message, ', ');

			$this->getUser()->setFlash('error', $message);
			return sfView::SUCCESS;
		}
		$this->getUser()->setFlash('success', 'El sitio se guardó correctamente.');
		$this->redirect('site/index?name='.$site->getSlug());

	}else{
		$this->getUser()->setFlash('error', 'Hubo un error en la validación del sitio.');
		return sfView::SUCCESS;
	}
  }
}
